<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Book_Baozou extends Controller{

public function action_index()
{
}

public function action_list()
{
	$baozou = ORM::factory('baozou');
	if ($_GET)
	{
		$page = arr::get($_GET, 'page');
		$num_in_page = arr::get($_GET, 'num_in_page');
		$order = arr::get($_GET, 'order');
		if ($order != NULL)
		{
			switch ($order)
			{
			case 0:
				$baozou->order_by('create_time', 'DESC');
				break;
			case 1:
				$baozou->order_by('create_time', 'ASC');
				break;
			case 2:
				$baozou->order_by('download_count', 'DESC');
				break;
			default:
				break;
			}
		}
	}
	$query_result = $baozou->find_all();
	if (isset($page) AND isset($num_in_page))
	{
		$result = Book_Baozou::instance()->create_baozou_list(array_slice($query_result->as_array(), ($page - 1) * $num_in_page, $num_in_page));
	}
	else
	{
		$result = Book_Baozou::instance()->create_baozou_list($query_result->as_array());
	}
	json_Output::write($result);
}

public function action_image()
{
	$baozou_id = arr::get($_GET, 'baozou_id');
	if ($baozou_id)
    {
		$baozou = ORM::factory('baozou')->where('id', '=', $baozou_id)->find();
		if ($baozou->loaded())
		{
			Book_Baozou::instance()->render($baozou->image);
		}
		else
		{
			header("Status: 400 书id不存在");
		}
	}
	else
	{
		header("Status: 400 参数为空");
		return;
	}
}

public function action_thumbnail()
{
	$baozou_id = arr::get($_GET, 'baozou_id');
	if ($baozou_id)
    {
		$baozou = ORM::factory('baozou')->where('id', '=', $baozou_id)->find();
		if ($baozou->loaded())
		{
			Book_Baozou::instance()->render_thumb($baozou->image);
		}
		else
		{
			header("Status: 400 书id不存在");
			return;
		}
	}
	else
	{
		header("Status: 400 参数为空");
		return;
	}
}

public function action_rand()
{
	$rand_num = arr::get($_GET, 'num');
	if ($rand_num <= 0)
	{
		header("Status: 400 参数num小于等于0");
		return;
	}
	$baozou = ORM::factory('baozou');
	$query_result = $baozou->find_all();
	$query_result = ORM::factory('baozou')
		->order_by(DB::expr('RAND()'))
		->limit($rand_num)
		->find_all();
	$result = Book_Baozou::instance()->create_baozou_list($query_result->as_array());
	json_Output::write($result);
}

}



